<!DOCTYPE HTML>
<html lang="zh-CN">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="「力扣」第 72 题：编辑距离（困难）, 算法与数据结构入门教程">
    <meta name="description" content="Java、Python3 语言实现，「专题」教程持续更新中...">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <!-- Global site tag (gtag.js) - Google Analytics -->


    <title>「力扣」第 72 题：编辑距离（困难） | 算法与数据结构入门教程</title>
    <link rel="icon" type="image/png" href="/leetcode-algo/favicon.png">

    <link rel="stylesheet" type="text/css" href="/leetcode-algo/libs/awesome/css/all.css">
    <link rel="stylesheet" type="text/css" href="/leetcode-algo/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/leetcode-algo/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/leetcode-algo/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/leetcode-algo/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/leetcode-algo/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/leetcode-algo/css/my.css">

    <script src="/leetcode-algo/libs/jquery/jquery.min.js"></script>

<meta name="generator" content="Hexo 4.2.0"><link rel="alternate" href="/leetcode-algo/atom.xml" title="算法与数据结构入门教程" type="application/atom+xml">
<link rel="stylesheet" href="/leetcode-algo/css/prism-tomorrow.css" type="text/css">
<link rel="stylesheet" href="/leetcode-algo/css/prism-line-numbers.css" type="text/css"></head>


<body>
    <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/leetcode-algo/" class="waves-effect waves-light">
                    
                    <img src="/leetcode-algo/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">算法与数据结构入门教程</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/leetcode-algo/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>首页</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/leetcode-algo/tags" class="waves-effect waves-light">
      
      <i class="fas fa-tags" style="zoom: 0.6;"></i>
      
      <span>标签</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/leetcode-algo/categories" class="waves-effect waves-light">
      
      <i class="fas fa-bookmark" style="zoom: 0.6;"></i>
      
      <span>分类</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/leetcode-algo/archives" class="waves-effect waves-light">
      
      <i class="fas fa-archive" style="zoom: 0.6;"></i>
      
      <span>归档</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/leetcode-algo/about" class="waves-effect waves-light">
      
      <i class="fas fa-user-circle" style="zoom: 0.6;"></i>
      
      <span>关于</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/leetcode-algo/contact" class="waves-effect waves-light">
      
      <i class="fas fa-comments" style="zoom: 0.6;"></i>
      
      <span>留言板</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/leetcode-algo/friends" class="waves-effect waves-light">
      
      <i class="fas fa-address-book" style="zoom: 0.6;"></i>
      
      <span>友情链接</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="搜索" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>


<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/leetcode-algo/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">算法与数据结构入门教程</div>
        <div class="logo-desc">
            
            Java、Python3 语言实现，「专题」教程持续更新中...
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/leetcode-algo/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			首页
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/leetcode-algo/tags" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-tags"></i>
			
			标签
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/leetcode-algo/categories" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-bookmark"></i>
			
			分类
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/leetcode-algo/archives" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-archive"></i>
			
			归档
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/leetcode-algo/about" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-user-circle"></i>
			
			关于
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/leetcode-algo/contact" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-comments"></i>
			
			留言板
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/leetcode-algo/friends" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-address-book"></i>
			
			友情链接
		</a>
          
        </li>
        
        
        <li><div class="divider"></div></li>
        <li>
            <a href="https://github.com/blinkfox/hexo-theme-matery" class="waves-effect waves-light" target="_blank">
                <i class="fab fa-github-square fa-fw"></i>Fork Me
            </a>
        </li>
        
    </ul>
</div>


        </div>

        
            <style>
    .nav-transparent .github-corner {
        display: none !important;
    }

    .github-corner {
        position: absolute;
        z-index: 10;
        top: 0;
        right: 0;
        border: 0;
        transform: scale(1.1);
    }

    .github-corner svg {
        color: #0f9d58;
        fill: #fff;
        height: 64px;
        width: 64px;
    }

    .github-corner:hover .octo-arm {
        animation: a 0.56s ease-in-out;
    }

    .github-corner .octo-arm {
        animation: none;
    }

    @keyframes a {
        0%,
        to {
            transform: rotate(0);
        }
        20%,
        60% {
            transform: rotate(-25deg);
        }
        40%,
        80% {
            transform: rotate(10deg);
        }
    }
</style>

<a href="https://github.com/blinkfox/hexo-theme-matery" class="github-corner tooltipped hide-on-med-and-down" target="_blank"
   data-tooltip="Fork Me" data-position="left" data-delay="50">
    <svg viewBox="0 0 250 250" aria-hidden="true">
        <path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path>
        <path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2"
              fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path>
        <path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z"
              fill="currentColor" class="octo-body"></path>
    </svg>
</a>
        
    </nav>

</header>

    



<div class="bg-cover pd-header post-cover" style="background-image: url('/leetcode-algo/medias/featureimages/6.jpg')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <h1 class="description center-align post-title">「力扣」第 72 题：编辑距离（困难）</h1>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="/leetcode-algo/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        width: 345px;
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        margin: 35px 0 15px 0;
        padding-left: 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content {
        height: calc(100vh - 250px);
        overflow: auto;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;

        position: absolute;
        right: 23.5vw;
        display: block;
    }

    .toc-fixed .toc-link::before{
        position: fixed!important;/*当toc的位置改为fixed时，.toc-link::before也要改为fixed*/
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #toc-content .is-active-link::before {
        background-color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/leetcode-algo/tags/%E6%BB%91%E5%8A%A8%E7%AA%97%E5%8F%A3/">
                                <span class="chip bg-color">滑动窗口</span>
                            </a>
                        
                            <a href="/leetcode-algo/tags/%E5%93%88%E5%B8%8C%E8%A1%A8/">
                                <span class="chip bg-color">哈希表</span>
                            </a>
                        
                            <a href="/leetcode-algo/tags/%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%92/">
                                <span class="chip bg-color">动态规划</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fas fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/leetcode-algo/categories/%E4%B8%93%E9%A2%98-15%EF%BC%9A%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%92/" class="post-category">
                                专题 15：动态规划
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2018-04-13
                </div>
                

                

                

                

                
            </div>
        </div>
        <hr class="clearfix">
        <div class="card-content article-card-content">
            <div id="articleContent">
                <h2 id="「力扣」第-72-题：编辑距离（困难）"><a href="#「力扣」第-72-题：编辑距离（困难）" class="headerlink" title="「力扣」第 72 题：编辑距离（困难）"></a>「力扣」第 72 题：编辑距离（困难）</h2><ul>
<li>链接：<a href="https://leetcode-cn.com/problems/edit-distance" target="_blank" rel="noopener">https://leetcode-cn.com/problems/edit-distance</a></li>
<li>题解链接：<a href="https://leetcode-cn.com/problems/edit-distance/solution/dong-tai-gui-hua-java-by-liweiwei1419/" target="_blank" rel="noopener">https://leetcode-cn.com/problems/edit-distance/solution/dong-tai-gui-hua-java-by-liweiwei1419/</a></li>
</ul>
<blockquote>
<p>给你两个单词 word1 和 word2，请你计算出将 word1 转换成 word2 所使用的最少操作数 。</p>
<p>你可以对一个单词进行如下三种操作：</p>
<ol>
<li>插入一个字符</li>
<li>删除一个字符</li>
<li>替换一个字符</li>
</ol>
<p>示例 1：</p>
<pre><code>输入：word1 = &quot;horse&quot;, word2 = &quot;ros&quot;
输出：3
解释：
horse -&gt; rorse (将 &#39;h&#39; 替换为 &#39;r&#39;)
rorse -&gt; rose (删除 &#39;r&#39;)
rose -&gt; ros (删除 &#39;e&#39;)</code></pre><p>示例 2：</p>
<pre><code>输入：word1 = &quot;intention&quot;, word2 = &quot;execution&quot;
输出：5
解释：
intention -&gt; inention (删除 &#39;t&#39;)
inention -&gt; enention (将 &#39;i&#39; 替换为 &#39;e&#39;)
enention -&gt; exention (将 &#39;n&#39; 替换为 &#39;x&#39;)
exention -&gt; exection (将 &#39;n&#39; 替换为 &#39;c&#39;)
exection -&gt; execution (插入 &#39;u&#39;)</code></pre></blockquote>
<p>这个问题是使用「动态规划」解决的的经典问题，一般是作为例题进行学习的，因此就直接给出「动态规划」方法的解释，主要在理解「动态规划」是如何定义「状态」和推导「状态转移方程」。</p>
<p>思路：</p>
<ul>
<li>「动态规划」告诉我们可以「自底向上」去考虑一个问题，思路是：<strong>先想这个问题最开始是什么情况，这个问题是两个字符串都为空字符的时候，然后逐个地，一个字符一个字符加上去，在加字符的过程中考虑「状态转移」</strong>；</li>
<li>由于要考虑空字符，因此状态空间要多设置一行、多设置一列。</li>
</ul>
<h3 id="方法：动态规划"><a href="#方法：动态规划" class="headerlink" title="方法：动态规划"></a>方法：动态规划</h3><h4 id="第-1-步：定义状态"><a href="#第-1-步：定义状态" class="headerlink" title="第 1 步：定义状态"></a>第 1 步：定义状态</h4><p>状态：<code>dp[i][j]</code> 表示将 <code>word1[0, i)</code> 转换成为 <code>word2[0, j)</code> 的方案数。</p>
<p>思考状态的方法：1、题目问什么就将什么定义为状态；2、「状态转移方程」怎么好推导，就怎么定义状态；3、根据经验和问题的特点（只有多做题了）。</p>
<p>说明：<strong>由于要考虑空字符</strong>，这里的下标 <code>i</code> 不包括 <code>word[i]</code>，同理下标 <code>j</code> 不包括 <code>word[j]</code>，从行数和列数多设置一行、一列也可以来理解这一点，也就是状态的下标 <code>i</code> 和 <code>j</code> 和字符的下标 <code>i</code>、<code>j</code> 有一个位置的偏差。</p>
<p>下文有些地方是 <code>)</code> 有些地方是 <code>]</code> 。如果造成疑惑，可以暂时不管，并不影响理解思想。</p>
<h4 id="第-2-步：思考状态转移方程"><a href="#第-2-步：思考状态转移方程" class="headerlink" title="第 2 步：思考状态转移方程"></a>第 2 步：思考状态转移方程</h4><p>状态转移方程通常是在做分类讨论，而分类讨论的过程，常常利用了这个问题的「最优子结构」。</p>
<h5 id="情况-1：word1-i-word2-j"><a href="#情况-1：word1-i-word2-j" class="headerlink" title="情况 1：word1[i] == word2[j]"></a>情况 1：<code>word1[i] == word2[j]</code></h5><p>如果 <code>word1[i] == word2[j]</code> 成立，则将 <code>word1[0, i)</code> 转换成为 <code>word2[0, j)</code> 的方案数就等于 将 <code>word1[0, i - 1)</code> 转换成为 <code>word2[0, j - 1)</code> 的方案数，即：</p>
<pre class="line-numbers language-java"><code class="language-java">dp<span class="token punctuation">[</span>i <span class="token operator">+</span> <span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">[</span>j <span class="token operator">+</span> <span class="token number">1</span><span class="token punctuation">]</span> <span class="token operator">=</span> dp<span class="token punctuation">[</span>i<span class="token punctuation">]</span><span class="token punctuation">[</span>j<span class="token punctuation">]</span>；<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p><strong>注意：这种情况，方案数最少，后面三种情况可以不用再讨论。</strong></p>
<ul>
<li>直觉：后面的情况要考虑的字符更多，并且还会增加 1 步操作；</li>
<li>实验：从实际代码运行的结果上看，可以通过测评，并且的确是后面的情况不会使得结果更少，大家还可以使用 <code>aaaa</code> 和 <code>aaaaa</code> 这样的情况去验证。</li>
</ul>
<p>对于这个结论 <a href="/u/1dUv8IogjC/">@1dUv8IogjC</a> 这位朋友给出了使用「数学归纳法」的证明，欢迎大家在评论区围观，感谢这位朋友。</p>
<p>也可以参考 <a href="/u/gelthin/">@gelthin</a> 这位朋友给出的题解：<a href="https://leetcode-cn.com/problems/edit-distance/solution/gelthin-jiao-ke-shu-biao-zhun-dp-by-gelthin/" target="_blank" rel="noopener">《证明: 当 w1[i] == w2[j]时，必有 DP[i+1][j+1] = DP[i][j]》</a>。</p>
<h5 id="情况-2：word1-i-word2-j"><a href="#情况-2：word1-i-word2-j" class="headerlink" title="情况 2：word1[i] != word2[j]"></a>情况 2：<code>word1[i] != word2[j]</code></h5><p>（下面的文字看过去文绉绉的，意会就可以了，建议尝试自己举例去理解。）</p>
<p>如果 <code>word1[i] != word2[j]</code> ，则将 <code>word1[0, i)</code> 转换成为 <code>word2[0, j)</code> 的方案数就等于下面 3 种情况的最少操作数（「最优子结构」）：</p>
<ol>
<li>考虑修改 <code>word1[i]</code> 成为 <code>word2[j]</code>；</li>
</ol>
<p>此时 <code>dp[i + 1][j + 1] = dp[i][j] + 1</code>，这里的 <code>1</code> 代表了将 <code>word1[i]</code> 替换成为 <code>word2[j]</code> 这一步操作。</p>
<ol start="2">
<li>考虑将 <code>word1[0, i]</code> 的最后一个字符删除；</li>
</ol>
<p>此时 <code>word1[0, i - 1]</code> 到 <code>word2[0, j]</code> 的最少操作数 $+ 1$，就是这种方案数的最少操作数，即： <code>dp[i + 1][j + 1] = dp[i][j + 1] + 1</code>，这里的 <code>1</code> 代表了 <code>word1[0, i]</code> 的最后一个字符删除这一步操作。</p>
<ol start="3">
<li>考虑将 <code>word1[0, i]</code> 的末尾添加一个字符使得 <code>word1[i + 1] == word2[j]</code>；</li>
</ol>
<p>此时考虑方案的时候，由于 <code>word1[i + 1] == word2[j]</code>，状态转移就不应该考虑 <code>word2[j]</code>，因此 <code>word1[0, i]</code> 到 <code>word2[0, j - 1]</code> 的最少操作数 $+ 1$，就是这种方案数的最少操作数，即： <code>dp[i + 1][j + 1] = dp[i + 1][j] + 1</code>，这里的 <code>1</code> 代表了将 <code>word1[0, i]</code> 的末尾添加一个字符使得 <code>word1[i + 1] == word2[j]</code>。（注意：可以考虑一下为什么得先讨论 <code>word1[i] == word2[j]</code> 的情况。）</p>
<p>在这 3 种操作中取最小值。</p>
<pre class="line-numbers language-java"><code class="language-java">dp<span class="token punctuation">[</span>i <span class="token operator">+</span> <span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">[</span>j <span class="token operator">+</span> <span class="token number">1</span><span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token function">min</span><span class="token punctuation">(</span>dp<span class="token punctuation">[</span>i<span class="token punctuation">]</span><span class="token punctuation">[</span>j<span class="token punctuation">]</span><span class="token punctuation">,</span> dp<span class="token punctuation">[</span>i<span class="token punctuation">]</span><span class="token punctuation">[</span>j <span class="token operator">+</span> <span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">,</span> dp<span class="token punctuation">[</span>i <span class="token operator">+</span> <span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">[</span>j<span class="token punctuation">]</span><span class="token punctuation">)</span> <span class="token operator">+</span> <span class="token number">1</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<h3 id="第-3-步：初始化"><a href="#第-3-步：初始化" class="headerlink" title="第 3 步：初始化"></a>第 3 步：初始化</h3><ul>
<li>从一个字符串变成空字符串，非空字符串的长度就是编辑距离；</li>
<li>以下代码其实就是在填表格的第 $0$ 行、第 $0$ 列。</li>
</ul>
<pre class="line-numbers language-java"><code class="language-java"><span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">int</span> i <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator">&lt;=</span> len1<span class="token punctuation">;</span> i<span class="token operator">++</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    dp<span class="token punctuation">[</span>i<span class="token punctuation">]</span><span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span> <span class="token operator">=</span> i<span class="token punctuation">;</span>
<span class="token punctuation">}</span>

<span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">int</span> j <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span> j <span class="token operator">&lt;=</span> len2<span class="token punctuation">;</span> j<span class="token operator">++</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    dp<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span><span class="token punctuation">[</span>j<span class="token punctuation">]</span> <span class="token operator">=</span> j<span class="token punctuation">;</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h3 id="第-4-步：-思考输出"><a href="#第-4-步：-思考输出" class="headerlink" title="第 4 步： 思考输出"></a>第 4 步： 思考输出</h3><p>输出：<code>dp[len1][len2]</code> 符合语义，即 <code>word1[0, len)</code> 转换成 <code>word2[0, len2)</code> 的最小操作数。（这里 <code>)</code> 表示开区间。）</p>
<h3 id="第-5-步：-思考状态压缩"><a href="#第-5-步：-思考状态压缩" class="headerlink" title="第 5 步： 思考状态压缩"></a>第 5 步： 思考状态压缩</h3><p>我们看一下「状态转移方程」：</p>
<ul>
<li>如果末尾字符相等，就「抄」左上角单元格的值；</li>
<li>如果末尾字符不相等，就从「正上方」、「左边」、「左上角」三个单元格的值中选出最小的 + 1。</li>
</ul>
<p>因此，初看可以使用「滚动数组」，更极端一点，用 $2 \times 2$ 表格就可以完成操作。但是真正去做「状态压缩」的时候，由于初始化的原因，发现没有那么容易，在这里不做「状态压缩」。（事实上可以压缩，但是只要是压缩状态，必然给编码造成一定困难，并且破坏代码可读性，根据情况做吧，个人觉得在空间紧张的情况下必须压缩空间，其余不必。）</p>
<p><strong>建议</strong>：自己动手填表格，加深体会「动态规划」的「自底向上」<strong>填表格</strong>解决问题的方法，它不是直接针对问题求解，而是从一个最小的情况开始，逐步递推，并且记录中间过程，得到最终答案的过程。</p>
<p>说明：手动填一下这张表格，体会：</p>
<ul>
<li>在末尾的两个字符相等的情况下，直接把左上角的值抄下来；</li>
</ul>
<p><img src="https://pic.leetcode-cn.com/ebe115d177b8bd39f14d6ac388d6cf419b0d2ce6c02bb27a761a5fc97bbae705-image.png" alt="image.png">{:width=”220px”}</p>
<ul>
<li>在末尾的两个字符不相等的情况下，「正上方」、「左边」、「左上角」三个单元格的值中选出最小的 + 1</li>
</ul>
<p><img src="https://pic.leetcode-cn.com/fd2898972926c756aef0d1d9898ac3aaf784cbc8e51945e90b4f58b295068450-image.png" alt="image.png">{:width=”200px”}</p>
<p>手填的时候一不小心很容易出错，然后去比对正确的表格，看看是哪里出错了。</p>
<p><img src="https://pic.leetcode-cn.com/c0d1ae3bc62e44920008623c21cdc0de2ea377397ad9b8e2c0157b59ef2dbf07-image.png" alt="image.png"></p>
<p>输出：</p>
<pre><code>[0, 1, 2, 3]
[1, 1, 2, 3]
[2, 2, 1, 2]
[3, 2, 2, 2]
[4, 3, 3, 2]
[5, 4, 4, 3]</code></pre><p>发现有一个地方填错了，然后去思考原因。</p>
<h3 id="类似问题"><a href="#类似问题" class="headerlink" title="类似问题"></a>类似问题</h3><p>这其实是一类称之为区间型 dp 的问题，主要特征是：思考的时候可以先将大区间拆分成小区间，求解的时候由小区间的解得到大区间的解。大家可以做一下这些问题以加深体会做这一类问题的思路和技巧，体会可以使用「动态规划」求解的问题的三个特征：</p>
<ul>
<li>重叠子问题；</li>
<li>最优子结构；</li>
<li>无后效性。</li>
</ul>
<p>「力扣」上比较典型的区间型 dp 问题有：</p>
<ul>
<li>「力扣」第 5 题：<a href="https://leetcode-cn.com/problems/longest-palindromic-substring/" target="_blank" rel="noopener">最长回文子串</a>；</li>
<li>「力扣」第 1143 题：<a href="https://leetcode-cn.com/problems/longest-common-subsequence/" target="_blank" rel="noopener">最长公共子串</a>；</li>
<li>「力扣」第 877 题：<a href="https://leetcode-cn.com/problems/stone-game/solution/" target="_blank" rel="noopener">石子游戏</a>；</li>
<li>「力扣」第 10 题：<a href="https://leetcode-cn.com/problems/regular-expression-matching/" target="_blank" rel="noopener">正则表达式匹配</a>。</li>
</ul>
<p><strong>参考代码</strong>：</p>
<pre class="line-numbers language-java"><code class="language-java"><span class="token keyword">import</span> java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>Arrays<span class="token punctuation">;</span>

<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">Solution</span> <span class="token punctuation">{</span>

    <span class="token keyword">public</span> <span class="token keyword">int</span> <span class="token function">minDistance</span><span class="token punctuation">(</span>String word1<span class="token punctuation">,</span> String word2<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token comment" spellcheck="true">// 由于 word1.charAt(i) 操作会去检查下标是否越界，因此</span>
        <span class="token comment" spellcheck="true">// 在 Java 里，将字符串转换成字符数组是常见额操作</span>

        <span class="token keyword">char</span><span class="token punctuation">[</span><span class="token punctuation">]</span> word1Array <span class="token operator">=</span> word1<span class="token punctuation">.</span><span class="token function">toCharArray</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">char</span><span class="token punctuation">[</span><span class="token punctuation">]</span> word2Array <span class="token operator">=</span> word2<span class="token punctuation">.</span><span class="token function">toCharArray</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token keyword">int</span> len1 <span class="token operator">=</span> word1Array<span class="token punctuation">.</span>length<span class="token punctuation">;</span>
        <span class="token keyword">int</span> len2 <span class="token operator">=</span> word2Array<span class="token punctuation">.</span>length<span class="token punctuation">;</span>

        <span class="token comment" spellcheck="true">// 多开一行一列是为了保存边界条件，即字符长度为 0 的情况，这一点在字符串的动态规划问题中比较常见</span>
        <span class="token keyword">int</span><span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token punctuation">[</span><span class="token punctuation">]</span> dp <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">int</span><span class="token punctuation">[</span>len1 <span class="token operator">+</span> <span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">[</span>len2 <span class="token operator">+</span> <span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">;</span>

        <span class="token comment" spellcheck="true">// 初始化：当 word 2 长度为 0 时，将 word1 的全部删除</span>
        <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">int</span> i <span class="token operator">=</span> <span class="token number">1</span><span class="token punctuation">;</span> i <span class="token operator">&lt;=</span> len1<span class="token punctuation">;</span> i<span class="token operator">++</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
            dp<span class="token punctuation">[</span>i<span class="token punctuation">]</span><span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span> <span class="token operator">=</span> i<span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
        <span class="token comment" spellcheck="true">// 当 word1 长度为 0 时，就插入所有 word2 的字符</span>
        <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">int</span> j <span class="token operator">=</span> <span class="token number">1</span><span class="token punctuation">;</span> j <span class="token operator">&lt;=</span> len2<span class="token punctuation">;</span> j<span class="token operator">++</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
            dp<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span><span class="token punctuation">[</span>j<span class="token punctuation">]</span> <span class="token operator">=</span> j<span class="token punctuation">;</span>
        <span class="token punctuation">}</span>

        <span class="token comment" spellcheck="true">// 注意：填写 dp 数组的时候，由于初始化多设置了一行一列，横、纵坐标有个偏移</span>
        <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">int</span> i <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> len1<span class="token punctuation">;</span> i<span class="token operator">++</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
            <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">int</span> j <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span> j <span class="token operator">&lt;</span> len2<span class="token punctuation">;</span> j<span class="token operator">++</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
                <span class="token comment" spellcheck="true">// 这是最佳情况</span>
                <span class="token keyword">if</span> <span class="token punctuation">(</span>word1Array<span class="token punctuation">[</span>i<span class="token punctuation">]</span> <span class="token operator">==</span> word2Array<span class="token punctuation">[</span>j<span class="token punctuation">]</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
                    dp<span class="token punctuation">[</span>i <span class="token operator">+</span> <span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">[</span>j <span class="token operator">+</span> <span class="token number">1</span><span class="token punctuation">]</span> <span class="token operator">=</span> dp<span class="token punctuation">[</span>i<span class="token punctuation">]</span><span class="token punctuation">[</span>j<span class="token punctuation">]</span><span class="token punctuation">;</span>
                    <span class="token keyword">continue</span><span class="token punctuation">;</span>
                <span class="token punctuation">}</span>

                <span class="token comment" spellcheck="true">// 否则在以下三种情况中选出步骤最少的，这是「动态规划」的「最优子结构」</span>
                <span class="token comment" spellcheck="true">// 1、在下标 i 处插入一个字符</span>
                <span class="token keyword">int</span> insert <span class="token operator">=</span> dp<span class="token punctuation">[</span>i <span class="token operator">+</span> <span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">[</span>j<span class="token punctuation">]</span> <span class="token operator">+</span> <span class="token number">1</span><span class="token punctuation">;</span>
                <span class="token comment" spellcheck="true">// 2、替换一个字符</span>
                <span class="token keyword">int</span> replace <span class="token operator">=</span> dp<span class="token punctuation">[</span>i<span class="token punctuation">]</span><span class="token punctuation">[</span>j<span class="token punctuation">]</span> <span class="token operator">+</span> <span class="token number">1</span><span class="token punctuation">;</span>
                <span class="token comment" spellcheck="true">// 3、删除一个字符</span>
                <span class="token keyword">int</span> delete <span class="token operator">=</span> dp<span class="token punctuation">[</span>i<span class="token punctuation">]</span><span class="token punctuation">[</span>j <span class="token operator">+</span> <span class="token number">1</span><span class="token punctuation">]</span> <span class="token operator">+</span> <span class="token number">1</span><span class="token punctuation">;</span>
                dp<span class="token punctuation">[</span>i <span class="token operator">+</span> <span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">[</span>j <span class="token operator">+</span> <span class="token number">1</span><span class="token punctuation">]</span> <span class="token operator">=</span> Math<span class="token punctuation">.</span><span class="token function">min</span><span class="token punctuation">(</span>Math<span class="token punctuation">.</span><span class="token function">min</span><span class="token punctuation">(</span>insert<span class="token punctuation">,</span> replace<span class="token punctuation">)</span><span class="token punctuation">,</span> delete<span class="token punctuation">)</span><span class="token punctuation">;</span>

            <span class="token punctuation">}</span>
        <span class="token punctuation">}</span>

        <span class="token comment" spellcheck="true">// 打印状态表格进行调试</span>
<span class="token comment" spellcheck="true">//        for (int i = 0; i &lt;=len1; i++) {</span>
<span class="token comment" spellcheck="true">//            System.out.println(Arrays.toString(dp[i]));</span>
<span class="token comment" spellcheck="true">//        }</span>
        <span class="token keyword">return</span> dp<span class="token punctuation">[</span>len1<span class="token punctuation">]</span><span class="token punctuation">[</span>len2<span class="token punctuation">]</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">void</span> <span class="token function">main</span><span class="token punctuation">(</span>String<span class="token punctuation">[</span><span class="token punctuation">]</span> args<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        String word1 <span class="token operator">=</span> <span class="token string">"horse"</span><span class="token punctuation">;</span>
        String word2 <span class="token operator">=</span> <span class="token string">"ros"</span><span class="token punctuation">;</span>

        Solution solution <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Solution</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">int</span> res <span class="token operator">=</span> solution<span class="token punctuation">.</span><span class="token function">minDistance</span><span class="token punctuation">(</span>word1<span class="token punctuation">,</span> word2<span class="token punctuation">)</span><span class="token punctuation">;</span>
        System<span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>res<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p><strong>复杂度分析</strong>：</p>
<ul>
<li>时间复杂度 ：$O(MN)$，其中 $M$ 为 <code>word1</code> 的长度，$N$ 为 <code>word2</code> 的长度；</li>
<li>空间复杂度 ：$O(MN)$，状态表格的大小。</li>
</ul>
<hr>
<h2 id="动态规划基础问题整理"><a href="#动态规划基础问题整理" class="headerlink" title="动态规划基础问题整理"></a>动态规划基础问题整理</h2><p>「动态规划」问题没有套路，请大家根据情况掌握自己需要的部分，多做一些问题或许是有用的。</p>
<h4 id="第-1-部分：「动态规划」基本问题"><a href="#第-1-部分：「动态规划」基本问题" class="headerlink" title="第 1 部分：「动态规划」基本问题"></a>第 1 部分：「动态规划」基本问题</h4><ul>
<li>递归 + 记忆化：记忆化递归（记忆化搜索），这是「自上而下」的思路；</li>
<li>掌握「自底向上」递推求解问题的方法；</li>
<li>理解「重复子问题」、「最优子结构」、「无后效性」；</li>
<li>掌握「状态定义」、「状态转移方程」</li>
</ul>
<table>
<thead>
<tr>
<th>题目序号</th>
<th>题解</th>
<th>知识点</th>
<th>代码</th>
</tr>
</thead>
<tbody><tr>
<td><a href="https://leetcode-cn.com/problems/fibonacci-number/" target="_blank" rel="noopener">509. 斐波那契数（简单）</a></td>
<td></td>
<td>递归做一定要加缓存。</td>
<td></td>
</tr>
<tr>
<td><a href="https://leetcode-cn.com/problems/climbing-stairs/" target="_blank" rel="noopener">70. 爬楼梯（简单）</a></td>
<td><a href="https://blog.csdn.net/lw_power/article/details/103799112" target="_blank" rel="noopener">CSDN</a></td>
<td>和斐波拉契数是同一道问题。</td>
<td></td>
</tr>
</tbody></table>
<h4 id="第-2-部分：最优子结构"><a href="#第-2-部分：最优子结构" class="headerlink" title="第 2 部分：最优子结构"></a>第 2 部分：最优子结构</h4><table>
<thead>
<tr>
<th>题目序号</th>
<th>题解</th>
<th>知识点</th>
<th>代码</th>
</tr>
</thead>
<tbody><tr>
<td><a href="https://leetcode-cn.com/problems/perfect-squares/" target="_blank" rel="noopener">279. 完全平方数（中等）</a></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td><a href="https://leetcode-cn.com/problems/coin-change/" target="_blank" rel="noopener">322. 零钱兑换（中等）</a></td>
<td><a href="https://leetcode-cn.com/problems/coin-change/solution/dong-tai-gui-hua-shi-yong-wan-quan-bei-bao-wen-ti-/" target="_blank" rel="noopener">动态规划、使用「完全背包」问题思路、图的广度优先遍历</a></td>
<td></td>
<td></td>
</tr>
<tr>
<td><a href="https://leetcode-cn.com/problems/integer-break/" target="_blank" rel="noopener">343. 整数拆分（中等）</a></td>
<td><a href="https://leetcode-cn.com/problems/integer-break/solution/tan-xin-xuan-ze-xing-zhi-de-jian-dan-zheng-ming-py/" target="_blank" rel="noopener">“贪心选择”性质的简单证明、记忆化搜索、动态规划 （Python、Java）</a></td>
<td></td>
<td></td>
</tr>
</tbody></table>
<h4 id="第-3-部分：无后效性"><a href="#第-3-部分：无后效性" class="headerlink" title="第 3 部分：无后效性"></a>第 3 部分：无后效性</h4><table>
<thead>
<tr>
<th>题目序号</th>
<th>题解</th>
<th>知识点</th>
<th>代码</th>
</tr>
</thead>
<tbody><tr>
<td><a href="https://leetcode-cn.com/problems/house-robber/" target="_blank" rel="noopener">198. 打家劫舍（简单）</a></td>
<td></td>
<td>二维状态消除后效性</td>
<td></td>
</tr>
<tr>
<td><a href="https://leetcode-cn.com/problems/unique-paths/" target="_blank" rel="noopener">62. 不同路径（中等）</a></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td><a href="https://leetcode-cn.com/problems/unique-paths-ii/" target="_blank" rel="noopener">63. 不同路径 II（中等）</a></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody></table>
<h4 id="第-4-部分：经典问题（1）"><a href="#第-4-部分：经典问题（1）" class="headerlink" title="第 4 部分：经典问题（1）"></a>第 4 部分：经典问题（1）</h4><table>
<thead>
<tr>
<th>题目序号</th>
<th>题解</th>
<th>知识点</th>
<th>代码</th>
</tr>
</thead>
<tbody><tr>
<td><a href="https://leetcode-cn.com/problems/maximum-subarray" target="_blank" rel="noopener">53. 最大子序和</a></td>
<td><a href="https://leetcode-cn.com/problems/maximum-subarray/solution/dong-tai-gui-hua-fen-zhi-fa-python-dai-ma-java-dai/" target="_blank" rel="noopener">动态规划、分治法</a>、<a href="https://blog.csdn.net/lw_power/article/details/104062895" target="_blank" rel="noopener">CSDN</a></td>
<td>1、经典动态规划问题；2、分治</td>
<td></td>
</tr>
<tr>
<td><a href="https://leetcode-cn.com/problems/longest-increasing-subsequence/" target="_blank" rel="noopener">300. 最长上升子序列</a></td>
<td><a href="https://leetcode-cn.com/problems/longest-increasing-subsequence/solution/dong-tai-gui-hua-er-fen-cha-zhao-tan-xin-suan-fa-p/" target="_blank" rel="noopener">动态规划 、贪心算法 + 二分</a></td>
<td></td>
<td></td>
</tr>
<tr>
<td><a href="https://leetcode-cn.com/problems/longest-palindromic-substring/" target="_blank" rel="noopener">5. 最长回文子串</a></td>
<td><a href="https://leetcode-cn.com/problems/longest-palindromic-substring/solution/zhong-xin-kuo-san-dong-tai-gui-hua-by-liweiwei1419/" target="_blank" rel="noopener">Manacher 算法 + 动态规划 （Java、C++、Python）</a></td>
<td>使用动态规划的方法得到子串的回文性质</td>
<td></td>
</tr>
<tr>
<td><a href="https://leetcode-cn.com/problems/edit-distance/" target="_blank" rel="noopener">72. 编辑距离</a></td>
<td><a href="https://leetcode-cn.com/problems/edit-distance/solution/dong-tai-gui-hua-java-by-liweiwei1419/" target="_blank" rel="noopener">动态规划（Java）</a>、<a href="https://blog.csdn.net/lw_power/article/details/103818533" target="_blank" rel="noopener">CDSN</a></td>
<td></td>
<td></td>
</tr>
<tr>
<td><a href="https://leetcode-cn.com/problems/triangle/" target="_blank" rel="noopener">120. 三角形最小路径和（中等）</a></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td><a href="https://leetcode-cn.com/problems/regular-expression-matching/" target="_blank" rel="noopener">10. 正则表达式匹配（困难）</a></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>#### 第 5 部分：经典问题（2）背包问题</td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody></table>
<table>
<thead>
<tr>
<th>题目序号</th>
<th>题解</th>
<th>知识点</th>
<th>代码</th>
</tr>
</thead>
<tbody><tr>
<td><a href="https://leetcode-cn.com/problems/partition-equal-subset-sum/" target="_blank" rel="noopener">416. 分割等和子集</a></td>
<td><a href="https://leetcode-cn.com/problems/partition-equal-subset-sum/solution/0-1-bei-bao-wen-ti-xiang-jie-zhen-dui-ben-ti-de-yo/" target="_blank" rel="noopener">动态规划（0-1 背包问题）</a></td>
<td>很重要的动态规划模型，必须掌握</td>
<td></td>
</tr>
<tr>
<td><a href="https://leetcode-cn.com/problems/coin-change-2/" target="_blank" rel="noopener">518. 零钱兑换 II</a></td>
<td><a href="https://leetcode-cn.com/problems/coin-change-2/solution/dong-tai-gui-hua-wan-quan-bei-bao-wen-ti-by-liweiw/" target="_blank" rel="noopener">动态规划（套用完全背包问题模型）</a></td>
<td></td>
<td></td>
</tr>
<tr>
<td><a href="https://leetcode-cn.com/problems/coin-change/" target="_blank" rel="noopener">322. 零钱兑换（中等）</a></td>
<td><a href="https://leetcode-cn.com/problems/coin-change/solution/dong-tai-gui-hua-shi-yong-wan-quan-bei-bao-wen-ti-/" target="_blank" rel="noopener">动态规划、使用「完全背包」问题思路、图的广度优先遍历</a></td>
<td></td>
<td></td>
</tr>
<tr>
<td><a href="https://leetcode-cn.com/problems/combination-sum-iv/" target="_blank" rel="noopener">377. 组合总和 Ⅳ</a></td>
<td><a href="https://leetcode-cn.com/problems/combination-sum-iv/solution/dong-tai-gui-hua-python-dai-ma-by-liweiwei1419/" target="_blank" rel="noopener">动态规划</a></td>
<td></td>
<td></td>
</tr>
<tr>
<td><a href="https://leetcode-cn.com/problems/target-sum/" target="_blank" rel="noopener">494. 目标和</a></td>
<td></td>
<td>0-1 背包问题</td>
<td></td>
</tr>
<tr>
<td><a href="https://leetcode-cn.com/problems/ones-and-zeroes/" target="_blank" rel="noopener">474. 一和零</a></td>
<td><a href="https://leetcode-cn.com/problems/ones-and-zeroes/solution/dong-tai-gui-hua-zhuan-huan-wei-0-1-bei-bao-wen-ti/" target="_blank" rel="noopener">动态规划（转换为 0-1 背包问题）</a></td>
<td></td>
<td></td>
</tr>
</tbody></table>
<h4 id="第-6-部分：经典问题（3）股票问题"><a href="#第-6-部分：经典问题（3）股票问题" class="headerlink" title="第 6 部分：经典问题（3）股票问题"></a>第 6 部分：经典问题（3）股票问题</h4><table>
<thead>
<tr>
<th>题目序号</th>
<th>题解</th>
<th>知识点</th>
<th>代码</th>
</tr>
</thead>
<tbody><tr>
<td><a href="https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock/" target="_blank" rel="noopener">121. 买卖股票的最佳时机（简单）</a></td>
<td><a href="https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock/solution/bao-li-mei-ju-dong-tai-gui-hua-chai-fen-si-xiang-b/" target="_blank" rel="noopener">暴力枚举 + 动态规划 + 差分思想</a>、<a href="https://blog.csdn.net/lw_power/article/details/103772951" target="_blank" rel="noopener">CSDN</a></td>
<td></td>
<td></td>
</tr>
<tr>
<td><a href="https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-ii/" target="_blank" rel="noopener">122. 买卖股票的最佳时机 II（简单）</a></td>
<td><a href="https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-ii/solution/tan-xin-suan-fa-by-liweiwei1419-2/" target="_blank" rel="noopener">暴力搜索 + 贪心算法 + 动态规划</a>、<a href="https://blog.csdn.net/lw_power/article/details/103773246" target="_blank" rel="noopener">CSDN</a></td>
<td></td>
<td></td>
</tr>
<tr>
<td><a href="https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-iii/" target="_blank" rel="noopener">123. 买卖股票的最佳时机 III（困难）</a></td>
<td><a href="https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-iii/solution/dong-tai-gui-hua-by-liweiwei1419-7/" target="_blank" rel="noopener">动态规划</a>、<a href="https://blog.csdn.net/lw_power/article/details/103773822" target="_blank" rel="noopener">CSDN</a></td>
<td>1、从后向前写可以把状态压缩到一维；2、分解成两个 121 题。</td>
<td></td>
</tr>
<tr>
<td><a href="https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-iv/" target="_blank" rel="noopener">188. 买卖股票的最佳时机 IV（困难）</a></td>
<td><a href="https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-iv/solution/dong-tai-gui-hua-by-liweiwei1419-4/" target="_blank" rel="noopener">动态规划</a></td>
<td></td>
<td></td>
</tr>
<tr>
<td><a href="https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/" target="_blank" rel="noopener">309. 最佳买卖股票时机含冷冻期（中等）</a></td>
<td><a href="https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/solution/dong-tai-gui-hua-by-liweiwei1419-5/" target="_blank" rel="noopener">动态规划</a></td>
<td></td>
<td></td>
</tr>
<tr>
<td><a href="https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/" target="_blank" rel="noopener">714. 买卖股票的最佳时机含手续费（中等）</a></td>
<td><a href="https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/solution/dong-tai-gui-hua-by-liweiwei1419-6/" target="_blank" rel="noopener">动态规划</a></td>
<td></td>
<td></td>
</tr>
</tbody></table>

            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        文章作者：
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://liweiwei1419.gitee.io/leetcode-algo" rel="external nofollow noreferrer">liweiwei419</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        文章链接：
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://liweiwei1419.gitee.io/leetcode-algo/2018/04/13/leetcode-algo/0072-edit-distance/">https://liweiwei1419.gitee.io/leetcode-algo/2018/04/13/leetcode-algo/0072-edit-distance/</a>
                    <!-- GitHub 用配置
                    <a href="https://liweiwei1419.gitee.io/leetcode-algo/leetcode-algo/2018/04/13/leetcode-algo/0072-edit-distance/">https://liweiwei1419.gitee.io/leetcode-algo/leetcode-algo/2018/04/13/leetcode-algo/0072-edit-distance/</a>
                    -->
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        版权声明：
                    </i>
                </span>
                <span class="reprint-info">
                    本博客所有文章除特別声明外，均采用
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    许可协议。转载请注明来源
                    <a href="https://liweiwei1419.gitee.io/leetcode-algo" target="_blank">liweiwei419</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>复制成功，请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/leetcode-algo/tags/%E6%BB%91%E5%8A%A8%E7%AA%97%E5%8F%A3/">
                                    <span class="chip bg-color">滑动窗口</span>
                                </a>
                            
                                <a href="/leetcode-algo/tags/%E5%93%88%E5%B8%8C%E8%A1%A8/">
                                    <span class="chip bg-color">哈希表</span>
                                </a>
                            
                                <a href="/leetcode-algo/tags/%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%92/">
                                    <span class="chip bg-color">动态规划</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/leetcode-algo/libs/share/css/share.min.css">
<div id="article-share">

    
    <div class="social-share" data-sites="twitter,facebook,google,qq,qzone,wechat,weibo,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/leetcode-algo/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
                <style>
    #reward {
        margin: 40px 0;
        text-align: center;
    }

    #reward .reward-link {
        font-size: 1.4rem;
        line-height: 38px;
    }

    #reward .btn-floating:hover {
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2), 0 5px 15px rgba(0, 0, 0, 0.2);
    }

    #rewardModal {
        width: 320px;
        height: 350px;
    }

    #rewardModal .reward-title {
        margin: 15px auto;
        padding-bottom: 5px;
    }

    #rewardModal .modal-content {
        padding: 10px;
    }

    #rewardModal .close {
        position: absolute;
        right: 15px;
        top: 15px;
        color: rgba(0, 0, 0, 0.5);
        font-size: 1.3rem;
        line-height: 20px;
        cursor: pointer;
    }

    #rewardModal .close:hover {
        color: #ef5350;
        transform: scale(1.3);
        -moz-transform:scale(1.3);
        -webkit-transform:scale(1.3);
        -o-transform:scale(1.3);
    }

    #rewardModal .reward-tabs {
        margin: 0 auto;
        width: 210px;
    }

    .reward-tabs .tabs {
        height: 38px;
        margin: 10px auto;
        padding-left: 0;
    }

    .reward-content ul {
        padding-left: 0 !important;
    }

    .reward-tabs .tabs .tab {
        height: 38px;
        line-height: 38px;
    }

    .reward-tabs .tab a {
        color: #fff;
        background-color: #ccc;
    }

    .reward-tabs .tab a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .reward-tabs .wechat-tab .active {
        color: #fff !important;
        background-color: #22AB38 !important;
    }

    .reward-tabs .alipay-tab .active {
        color: #fff !important;
        background-color: #019FE8 !important;
    }

    .reward-tabs .reward-img {
        width: 210px;
        height: 210px;
    }
</style>

<div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-medium waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fas fa-times"></i></a>
            <h4 class="reward-title">你的赏识是我前进的动力</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        <img src="/leetcode-algo/medias/reward/alipayimg.png" class="reward-img" alt="支付宝打赏二维码">
                    </div>
                    <div id="wechat">
                        <img src="/leetcode-algo/medias/reward/wechatpayimg.png" class="reward-img" alt="微信打赏二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>

            
        </div>
    </div>

    

    

    

    

    
        <style>
    .valine-card {
        margin: 1.5rem auto;
    }

    .valine-card .card-content {
        padding: 20px 20px 5px 20px;
    }

    #vcomments textarea {
        box-sizing: border-box;
        background: url("/leetcode-algo/medias/comment_bg.png") 100% 100% no-repeat;
    }

    #vcomments p {
        margin: 2px 2px 10px;
        font-size: 1.05rem;
        line-height: 1.78rem;
    }

    #vcomments blockquote p {
        text-indent: 0.2rem;
    }

    #vcomments a {
        padding: 0 2px;
        color: #4cbf30;
        font-weight: 500;
        text-decoration: none;
    }

    #vcomments img {
        max-width: 100%;
        height: auto;
        cursor: pointer;
    }

    #vcomments ol li {
        list-style-type: decimal;
    }

    #vcomments ol,
    ul {
        display: block;
        padding-left: 2em;
        word-spacing: 0.05rem;
    }

    #vcomments ul li,
    ol li {
        display: list-item;
        line-height: 1.8rem;
        font-size: 1rem;
    }

    #vcomments ul li {
        list-style-type: disc;
    }

    #vcomments ul ul li {
        list-style-type: circle;
    }

    #vcomments table, th, td {
        padding: 12px 13px;
        border: 1px solid #dfe2e5;
    }

    #vcomments table, th, td {
        border: 0;
    }

    table tr:nth-child(2n), thead {
        background-color: #fafafa;
    }

    #vcomments table th {
        background-color: #f2f2f2;
        min-width: 80px;
    }

    #vcomments table td {
        min-width: 80px;
    }

    #vcomments h1 {
        font-size: 1.85rem;
        font-weight: bold;
        line-height: 2.2rem;
    }

    #vcomments h2 {
        font-size: 1.65rem;
        font-weight: bold;
        line-height: 1.9rem;
    }

    #vcomments h3 {
        font-size: 1.45rem;
        font-weight: bold;
        line-height: 1.7rem;
    }

    #vcomments h4 {
        font-size: 1.25rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    #vcomments h5 {
        font-size: 1.1rem;
        font-weight: bold;
        line-height: 1.4rem;
    }

    #vcomments h6 {
        font-size: 1rem;
        line-height: 1.3rem;
    }

    #vcomments p {
        font-size: 1rem;
        line-height: 1.5rem;
    }

    #vcomments hr {
        margin: 12px 0;
        border: 0;
        border-top: 1px solid #ccc;
    }

    #vcomments blockquote {
        margin: 15px 0;
        border-left: 5px solid #42b983;
        padding: 1rem 0.8rem 0.3rem 0.8rem;
        color: #666;
        background-color: rgba(66, 185, 131, .1);
    }

    #vcomments pre {
        font-family: monospace, monospace;
        padding: 1.2em;
        margin: .5em 0;
        background: #272822;
        overflow: auto;
        border-radius: 0.3em;
        tab-size: 4;
    }

    #vcomments code {
        font-family: monospace, monospace;
        padding: 1px 3px;
        font-size: 0.92rem;
        color: #e96900;
        background-color: #f8f8f8;
        border-radius: 2px;
    }

    #vcomments pre code {
        font-family: monospace, monospace;
        padding: 0;
        color: #e8eaf6;
        background-color: #272822;
    }

    #vcomments pre[class*="language-"] {
        padding: 1.2em;
        margin: .5em 0;
    }

    #vcomments code[class*="language-"],
    pre[class*="language-"] {
        color: #e8eaf6;
    }

    #vcomments [type="checkbox"]:not(:checked), [type="checkbox"]:checked {
        position: inherit;
        margin-left: -1.3rem;
        margin-right: 0.4rem;
        margin-top: -1px;
        vertical-align: middle;
        left: unset;
        visibility: visible;
    }

    #vcomments b,
    strong {
        font-weight: bold;
    }

    #vcomments dfn {
        font-style: italic;
    }

    #vcomments small {
        font-size: 85%;
    }

    #vcomments cite {
        font-style: normal;
    }

    #vcomments mark {
        background-color: #fcf8e3;
        padding: .2em;
    }

    #vcomments table, th, td {
        padding: 12px 13px;
        border: 1px solid #dfe2e5;
    }

    table tr:nth-child(2n), thead {
        background-color: #fafafa;
    }

    #vcomments table th {
        background-color: #f2f2f2;
        min-width: 80px;
    }

    #vcomments table td {
        min-width: 80px;
    }

    #vcomments [type="checkbox"]:not(:checked), [type="checkbox"]:checked {
        position: inherit;
        margin-left: -1.3rem;
        margin-right: 0.4rem;
        margin-top: -1px;
        vertical-align: middle;
        left: unset;
        visibility: visible;
    }
</style>

<div class="card valine-card" data-aos="fade-up">
    <div class="comment_headling" style="font-size: 20px; font-weight: 700; position: relative; padding-left: 20px; top: 15px; padding-bottom: 5px;">
        <i class="fas fa-comments fa-fw" aria-hidden="true"></i>
        <span>评论</span>
    </div>
    <div id="vcomments" class="card-content" style="display: grid">
    </div>
</div>

<script src="/leetcode-algo/libs/valine/av-min.js"></script>
<script src="/leetcode-algo/libs/valine/Valine.min.js"></script>
<script>
    new Valine({
        el: '#vcomments',
        appId: 't85BdPqKV8IDpevPmRGUSquP-gzGzoHsz',
        appKey: 'AIarytPiYajpQ31kGdAMfVQ8',
        notify: 'false' === 'true',
        verify: 'false' === 'true',
        visitor: 'true' === 'true',
        avatar: 'mm',
        pageSize: '10',
        lang: 'zh-cn',
        placeholder: 'just go go'
    });
</script>

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/leetcode-algo/2018/04/14/leetcode-algo/0091-decode-ways/">
                    <div class="card-image">
                        
                        
                        <img src="/leetcode-algo/medias/featureimages/4.jpg" class="responsive-img" alt="「力扣」第 91 题：解码方法（中等）">
                        
                        <span class="card-title">「力扣」第 91 题：解码方法（中等）</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            「力扣」第 91 题：解码方法（中等）
1、画图；2、分类（用加法）、分步（用乘法）


链接
题解链接


要求：一条包含字母 A-Z 的消息通过以下方式进行了编码：
&#39;A&#39; -&gt; 1
&#39;B&#39; -&g
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2018-04-14
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/leetcode-algo/categories/%E4%B8%93%E9%A2%98-15%EF%BC%9A%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%92/" class="post-category">
                                    专题 15：动态规划
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/leetcode-algo/tags/%E5%AD%97%E7%AC%A6%E4%B8%B2/">
                        <span class="chip bg-color">字符串</span>
                    </a>
                    
                    <a href="/leetcode-algo/tags/%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%92/">
                        <span class="chip bg-color">动态规划</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/leetcode-algo/2018/04/12/leetcode-algo/0070-climbing-stairs/">
                    <div class="card-image">
                        
                        
                        <img src="/leetcode-algo/medias/featureimages/19.jpg" class="responsive-img" alt="「力扣」第 70 题：爬楼梯">
                        
                        <span class="card-title">「力扣」第 70 题：爬楼梯</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            「力扣」第 70 题：爬楼梯
斐波拉契数列，画出树形结构，发现大量重叠子问题。「动态规划」告诉我们「自顶向上」求解问题的思路。


链接
英文地址 


假设你正在爬楼梯。需要 n 阶你才能到达楼顶。
每次你可以爬 1 或 2 个台阶。你有
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2018-04-12
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/leetcode-algo/categories/%E4%B8%93%E9%A2%98-15%EF%BC%9A%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%92/" class="post-category">
                                    专题 15：动态规划
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/leetcode-algo/tags/%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%92/">
                        <span class="chip bg-color">动态规划</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>



<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/leetcode-algo/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="/leetcode-algo/libs/codeBlock/codeLang.js"></script>


<!-- 代码块复制 -->

<script type="text/javascript" src="/leetcode-algo/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/leetcode-algo/libs/codeBlock/codeShrink.js"></script>


<!-- 代码块折行 -->

<style type="text/css">
code[class*="language-"], pre[class*="language-"] { white-space: pre !important; }
</style>


    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/leetcode-algo/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            collapseDepth: Number('0'),
            headingSelector: 'h2, h3, h4'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h2, h3, h4').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>


<script src="https://cdn.bootcss.com/mathjax/2.7.5/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
<script>
    MathJax.Hub.Config({
        tex2jax: {inlineMath: [['$', '$'], ['\(', '\)']]}
    });
</script>



    <footer class="page-footer bg-color">
    
    <div class="container row center-align" style="margin-bottom: 0px !important;">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            <span id="year">2019</span>
            <a href="https://liweiwei1419.gitee.io/leetcode-algo" target="_blank">liweiwei1419</a>
            |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a>
            |&nbsp;Theme&nbsp;<a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a>
            <br>
            
            
            
            
            
            
            <span id="busuanzi_container_site_pv">
                |&nbsp;<i class="far fa-eye"></i>&nbsp;总访问量:&nbsp;<span id="busuanzi_value_site_pv"
                    class="white-color"></span>&nbsp;次
            </span>
            
            
            <span id="busuanzi_container_site_uv">
                |&nbsp;<i class="fas fa-users"></i>&nbsp;总访问人数:&nbsp;<span id="busuanzi_value_site_uv"
                    class="white-color"></span>&nbsp;人
            </span>
            
            <br>
            
            <br>
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis">
    <a href="https://github.com/liweiwei1419" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>



    <a href="mailto:liweiwei1419@gmail.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>







    <a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=121088825" class="tooltipped" target="_blank" data-tooltip="QQ联系我: 121088825" data-position="top" data-delay="50">
        <i class="fab fa-qq"></i>
    </a>



    <a href="https://weibo.com/u/2194939432" class="tooltipped" target="_blank" data-tooltip="关注我的微博: https://weibo.com/u/2194939432" data-position="top" data-delay="50">
        <i class="fab fa-weibo"></i>
    </a>





    <a href="/leetcode-algo/atom.xml" class="tooltipped" target="_blank" data-tooltip="RSS 订阅" data-position="top" data-delay="50">
        <i class="fas fa-rss"></i>
    </a>

</div>
    </div>
</footer>

<div class="progress-bar"></div>


    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script src="/leetcode-algo/js/search.js"></script>
<script type="text/javascript">
$(function () {
    searchFunc("/leetcode-algo/search.xml", 'searchInput', 'searchResult');
});
</script>

    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


    <script src="/leetcode-algo/libs/materialize/materialize.min.js"></script>
    <script src="/leetcode-algo/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/leetcode-algo/libs/aos/aos.js"></script>
    <script src="/leetcode-algo/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="/leetcode-algo/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="/leetcode-algo/js/matery.js"></script>

    <!-- Baidu Analytics -->

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    <script src="/leetcode-algo/libs/others/clicklove.js" async="async"></script>
    
    
    <script async src="/leetcode-algo/libs/others/busuanzi.pure.mini.js"></script>
    

    

    

    

    

    

    
    <script src="/leetcode-algo/libs/instantpage/instantpage.js" type="module"></script>
    

</body>

</html>
